package com.libgdxbar.pvzlikegame.systems.animation;

import com.badlogic.gdx.utils.IntMap;
import com.libgdxbar.pvzlikegame.entities.Entity;
import com.libgdxbar.pvzlikegame.entities.EntityListener;
import org.libgdxbar.projects.interfaces.animation.IAnimator;
import org.libgdxbar.projects.interfaces.renderer.ITextureRegion;

public class AnimationSystem extends Entity implements EntityListener {

	private IntMap<AnimatorEntity> animatorIntMap = new IntMap<>();

	@Override
	public void onEntityAdded(Entity entity) {
		if (isMatches(entity)) {
			animatorIntMap.put(entity.id, new AnimatorEntity(entity, new Animator()));
		}
	}

	@Override
	public void onEntityRemoved(Entity entity) {
		if (isMatches(entity)) {
			animatorIntMap.remove(entity.id);
		}
	}

	public boolean isMatches(Entity entity) {
		return entity instanceof ITextureRegion && entity instanceof IAnimator;
	}

	@Override
	public void run(float delta) {
		for (AnimatorEntity animatorEntity : animatorIntMap.values()) {
			Animator animator = animatorEntity.animator;
			ITextureRegion textureRegionable = (ITextureRegion) animatorEntity.entity;
			animator.update(delta);
			textureRegionable.setTextureRegion(animator.getFrame());
		}
	}

	class AnimatorEntity{
		private Entity entity;
		private Animator animator;

		public AnimatorEntity(Entity entity, Animator animator){
			this.entity = entity;
			this.animator = animator;
		}
	}
}
